import configparser

import openpyxl
import pytest
from base.logging_utils import *
from base.os_utils import *

# 初始化logging配置参数
pro_root_path = get_dir_name(__file__).replace("\\","/")
init_logging(pro_root_path)
logging.info(f"测试环境配置")
logging.info(f"当前项目根路径为:{pro_root_path}")

def pytest_addoption(parser):
    """
    pytest的添加命令行参数钩子函数
    :param parser: 必须传一个叫parser的参数
    :return: 无
    """
    logging.info("开始执行[pytest_addoption]钩子函数+++++++++++++++++++++++++++++++++++++++++++++++++++++")
    parser.addoption(
        "--env",
        action="store",
        default="test",
        help="环境运行时的环境配置参数"
    )
    logging.info("[pytest_addoption]钩子函数执行完毕+++++++++++++++++++++++++++++++++++++++++++++++++++++")

def pytest_configure(config):
    """
    pytest的获取命令行参数钩子函数
    :param config: 必须传一个叫config的参数,用来读取命令行传的参数
    :return: 无
    """
    logging.info("开始执行[pytest_configure]钩子函数+++++++++++++++++++++++++++++++++++++++++++++++++++++")

    env = config.getoption("--env")
    logging.info(f"获取到了命令行env的参数,值为:{env}")

    remote_cfg = configparser.ConfigParser()
    remote_cfg.read(pro_root_path + "/config/remote_enviromment_config.ini", encoding="utf-8")

    local_cfg = configparser.ConfigParser()
    local_cfg.read(pro_root_path + "/config/local_environment_config.ini", encoding="utf-8")

    base_url = None
    db_host = None
    db_port = None
    db_name = None
    db_user = None
    db_password = None
    excel_name = None
    sheet_name = None

    if env == "environment_one":
        logging.info("开始读取[environment_one]远程环境配置的参数信息+++++++++++++++++++++++++++++++++++++++++++++++++++++")
        base_url = remote_cfg.get("server_one","base_url")
        db_host = remote_cfg.get("database_one","db_host")
        db_port = remote_cfg.get("database_one", "db_port")
        db_name = remote_cfg.get("database_one", "db_name")
        db_user = remote_cfg.get("database_one", "db_user")
        db_password = remote_cfg.get("database_one", "db_password")

        logging.info("读取到的远程环境配置的参数信息:")
        logging.info(f"base_url:{base_url}")
        logging.info(f"db_host:{db_host}")
        logging.info(f"db_port:{db_port}")
        logging.info(f"db_name:{db_name}")
        logging.info(f"db_user:{db_user}")
        logging.info(f"db_password:{db_password}")

    if env == "environment_two":
        logging.info("开始读取[environment_two]远程环境配置的参数信息+++++++++++++++++++++++++++++++++++++++++++++++++++++")
        base_url = remote_cfg.get("server_two","base_url")
        db_host = remote_cfg.get("database_two","db_host")
        db_port = remote_cfg.get("database_two", "db_port")
        db_name = remote_cfg.get("database_two", "db_name")
        db_user = remote_cfg.get("database_two", "db_user")
        db_password = remote_cfg.get("database_two", "db_password")

        logging.info("读取到的远程环境配置的参数信息:")
        logging.info(f"base_url:{base_url}")
        logging.info(f"db_host:{db_host}")
        logging.info(f"db_port:{db_port}")
        logging.info(f"db_name:{db_name}")
        logging.info(f"db_user:{db_user}")
        logging.info(f"db_password:{db_password}")

    logging.info("将读取到的远程环境配置的参数信息设置到系统环境变量+++++++++++++++++++++++++++++++++++++++++++++++++++++")
    set_env_param("base_url",base_url)
    set_env_param("db_host", db_host)
    set_env_param("db_port", db_port)
    set_env_param("db_name", db_name)
    set_env_param("db_user", db_user)
    set_env_param("db_password", db_password)


    logging.info("当前系统环境变量中的远程环境参数信息:")
    logging.info(f"base_url:{get_env_param('base_url')}")
    logging.info(f"db_host:{get_env_param('db_host')}")
    logging.info(f"db_port:{get_env_param('db_port')}")
    logging.info(f"db_name:{get_env_param('db_name')}")
    logging.info(f"db_user:{get_env_param('db_user')}")
    logging.info(f"db_password:{get_env_param('db_password')}")

    logging.info("开始读取本地环境配置的参数信息+++++++++++++++++++++++++++++++++++++++++++++++++++++")
    excel_name = local_cfg.get("test_case_path","excel_name")
    sheet_name = local_cfg.get("test_case_path", "sheet_name")
    interface_max_time = local_cfg.get("slow_interface", "interface_max_time")
    is_count_interface = local_cfg.get("slow_interface", "is_count_interface")
    rsa_public_key = local_cfg.get("rsa", "public_key")
    rsa_private_key = local_cfg.get("rsa", "private_key")

    logging.info("读取到的本地环境配置的参数信息:")
    logging.info(f"excel_name:{excel_name}")
    logging.info(f"sheet_name:{sheet_name}")
    logging.info(f"interface_max_time:{interface_max_time}")
    logging.info(f"is_count_interface:{is_count_interface}")
    logging.info(f"rsa_public_key:{rsa_public_key}")
    logging.info(f"rsa_private_key:{rsa_private_key}")

    logging.info("将读取到的本地环境配置的参数信息设置到系统环境变量+++++++++++++++++++++++++++++++++++++++++++++++++++++")
    set_env_param("excel_name",excel_name)
    set_env_param("sheet_name", sheet_name)
    set_env_param("interface_max_time", interface_max_time)
    set_env_param("is_count_interface", is_count_interface)
    set_env_param("rsa_public_key", rsa_public_key)
    set_env_param("rsa_private_key", rsa_private_key)


    logging.info("当前系统环境变量中的本地环境参数信息:")

    logging.info(f"excel_name:{get_env_param('excel_name')}")
    logging.info(f"sheet_name:{get_env_param('sheet_name')}")
    logging.info(f"interface_max_time:{get_env_param('interface_max_time')}")
    logging.info(f"is_count_interface:{get_env_param('is_count_interface')}")
    logging.info(f"rsa_public_key:{get_env_param('rsa_public_key')}")
    logging.info(f"rsa_private_key:{get_env_param('rsa_private_key')}")

    logging.info("将项目根目录设置到系统环境变量+++++++++++++++++++++++++++++++++++++++++++++++++++++")
    set_env_param("pro_root_path", pro_root_path)
    logging.info("当前系统环境变量中的项目根目录信息:")
    logging.info(f"pro_root_path:{get_env_param('pro_root_path')}")

    logging.info("[pytest_configure]钩子函数执行完毕+++++++++++++++++++++++++++++++++++++++++++++++++++++")


def pytest_collection_modifyitems(items):
    logging.info("开始执行[pytest_collection_modifyitems]钩子函数+++++++++++++++++++++++++++++++++++++++++++++++++++++")
    for item in items:
        case_params = item.callspec.params["one_test_case_data_no_replace_variable"]
        if case_params["is_true"]:
            if case_params["retry_count"] > 0:
                logging.info(f"{item.name}测试用例函数设置了失败重试,重试次数:{case_params['retry_count']}次")
                item.add_marker(pytest.mark.flaky(reruns=case_params["retry_count"]))
        else :
            logging.info(f"{item.name}测试用例函数设置了跳过,本次测试不执行")
            item.add_marker(pytest.mark.skip())
    logging.info("[pytest_collection_modifyitems]钩子函数执行完毕+++++++++++++++++++++++++++++++++++++++++++++++++++++")



@pytest.fixture(autouse=True,scope="session")
def fixture_session():
    logging.info("测试前置函数 [fixture_session] 开始执行了++++++++++++++++++++++++++++++++++++++++++++++++")
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = '慢接口统计'

    cell_width = 50
    ws.column_dimensions["a"].width = cell_width
    ws.column_dimensions["b"].width = cell_width
    ws.column_dimensions["c"].width = cell_width
    ws.column_dimensions["d"].width = cell_width
    ws.column_dimensions["e"].width = cell_width
    ws.column_dimensions["f"].width = cell_width
    ws.column_dimensions["g"].width = cell_width
    ws.column_dimensions["h"].width = cell_width

    to_be_write_table_header = ["请求地址","请求方法","请求头参数","请求参数_params","请求参数_data","请求参数_json","请求参数_files","请求耗时(毫秒)"]

    ws.append(to_be_write_table_header)
    wb.save(get_env_param('pro_root_path') + "/test_report/slow_interface/慢接口统计.xlsx")

    logging.info("测试前置函数 [fixture_session] 执行完毕了++++++++++++++++++++++++++++++++++++++++++++++++")
    yield
    logging.info("测试后置函数 [fixture_session] 开始执行了++++++++++++++++++++++++++++++++++++++++++++++++")
    logging.info("测试后置函数 [fixture_session] 执行完毕了++++++++++++++++++++++++++++++++++++++++++++++++")


@pytest.fixture(autouse=True,scope="function")
def fixture_function():
    logging.info("测试前置函数 [fixture_function] 开始执行了++++++++++++++++++++++++++++++++++++++++++++++++")
    set_env_param("is_count_interface", str(1))
    logging.info(f"初始化断言是否成功状态标记为:{get_env_param('is_count_interface')}")
    logging.info("测试前置函数 [fixture_function] 执行完毕了++++++++++++++++++++++++++++++++++++++++++++++++")
    yield
    logging.info("测试后置函数 [fixture_function] 开始执行了++++++++++++++++++++++++++++++++++++++++++++++++")
    logging.info("测试后置函数 [fixture_function] 执行完毕了++++++++++++++++++++++++++++++++++++++++++++++++")